package com.knowledgeqa.system.controller;

import com.knowledgeqa.system.entity.Answer;
import com.knowledgeqa.system.entity.Question;
import com.knowledgeqa.system.entity.User;
import com.knowledgeqa.system.service.AnswerService;
import com.knowledgeqa.system.service.QuestionService;
import com.knowledgeqa.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 回答控制器
 */
@RestController
@RequestMapping("/api/answer")
public class AnswerController {

    @Autowired
    private AnswerService answerService;

    @Autowired
    private UserService userService;

    @Autowired
    private QuestionService questionService;

    /**
     * 回答问题
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addAnswer(@RequestBody Answer answer) {
        Map<String, Object> result = new HashMap<>();

        // 检查问题是否已关闭
        Long questionId = answer.getQuestionId();
        if (questionId != null) {
            Question question = questionService.findById(questionId);
            if (question != null && question.getStatus() == 2) { // 2表示已关闭状态
                result.put("success", false);
                result.put("message", "该问题已关闭，无法回答");
                return ResponseEntity.ok(result);
            }
        }

        boolean success = answerService.addAnswer(answer);
        result.put("success", success);
        result.put("message", success ? "回答成功" : "回答失败");
        return ResponseEntity.ok(result);
    }

    /**
     * 获取问题的所有回答
     */
    @GetMapping("/question/{questionId}")
    public ResponseEntity<Map<String, Object>> getQuestionAnswers(@PathVariable Long questionId) {
        Map<String, Object> result = new HashMap<>();
        List<Answer> answers = answerService.findByQuestionId(questionId);

        // 构建前端需要的回答信息列表，包含用户名
        List<Map<String, Object>> answerList = new ArrayList<>();
        for (Answer answer : answers) {
            Map<String, Object> answerInfo = new HashMap<>();

            // 复制原始回答的所有属性
            answerInfo.put("id", answer.getId());
            answerInfo.put("content", answer.getContent());
            answerInfo.put("createTime", answer.getCreateTime());
            answerInfo.put("isAccepted", answer.getIsAccepted());
            answerInfo.put("status", answer.getStatus());
            answerInfo.put("userId", answer.getUserId());
            answerInfo.put("questionId", answer.getQuestionId());

            // 获取回答者昵称或用户名
            try {
                User user = userService.findById(answer.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        answerInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        answerInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        answerInfo.put("username", "用户" + answer.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    answerInfo.put("username", "用户" + answer.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                answerInfo.put("username", "用户" + answer.getUserId());
            }

            answerList.add(answerInfo);
        }

        result.put("success", true);
        result.put("answers", answerList);
        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户的所有回答
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserAnswers(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        List<Answer> answers = answerService.findByUserId(userId);

        // 构建前端需要的回答信息列表，包含用户名
        List<Map<String, Object>> answerList = new ArrayList<>();
        for (Answer answer : answers) {
            Map<String, Object> answerInfo = new HashMap<>();

            // 复制原始回答的所有属性
            answerInfo.put("id", answer.getId());
            answerInfo.put("content", answer.getContent());
            answerInfo.put("createTime", answer.getCreateTime());
            answerInfo.put("isAccepted", answer.getIsAccepted());
            answerInfo.put("status", answer.getStatus());
            answerInfo.put("userId", answer.getUserId());
            answerInfo.put("questionId", answer.getQuestionId());

            // 获取回答者昵称或用户名
            try {
                User user = userService.findById(answer.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        answerInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        answerInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        answerInfo.put("username", "用户" + answer.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    answerInfo.put("username", "用户" + answer.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                answerInfo.put("username", "用户" + answer.getUserId());
            }

            answerList.add(answerInfo);
        }

        result.put("success", true);
        result.put("answers", answerList);
        return ResponseEntity.ok(result);
    }

    /**
     * 更新回答
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateAnswer(@RequestBody Answer answer) {
        Map<String, Object> result = new HashMap<>();
        boolean success = answerService.update(answer);
        result.put("success", success);
        result.put("message", success ? "回答更新成功" : "回答更新失败");
        return ResponseEntity.ok(result);
    }

    /**
     * 删除回答
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteAnswer(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        boolean success = answerService.deleteById(id);
        result.put("success", success);
        result.put("message", success ? "回答删除成功" : "回答删除失败");
        return ResponseEntity.ok(result);
    }

    /**
     * 获取问题的被采纳回答
     */
    @GetMapping("/accepted/{questionId}")
    public ResponseEntity<Map<String, Object>> getAcceptedAnswer(@PathVariable Long questionId) {
        Map<String, Object> result = new HashMap<>();
        Answer answer = answerService.findAcceptedAnswerByQuestionId(questionId);

        if (answer != null) {
            // 构建前端需要的回答信息，包含用户名
            Map<String, Object> answerInfo = new HashMap<>();

            // 复制原始回答的所有属性
            answerInfo.put("id", answer.getId());
            answerInfo.put("content", answer.getContent());
            answerInfo.put("createTime", answer.getCreateTime());
            answerInfo.put("isAccepted", answer.getIsAccepted());
            answerInfo.put("status", answer.getStatus());
            answerInfo.put("userId", answer.getUserId());
            answerInfo.put("questionId", answer.getQuestionId());

            // 获取回答者昵称或用户名
            try {
                User user = userService.findById(answer.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        answerInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        answerInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        answerInfo.put("username", "用户" + answer.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    answerInfo.put("username", "用户" + answer.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                answerInfo.put("username", "用户" + answer.getUserId());
            }

            result.put("answer", answerInfo);
        }

        result.put("success", answer != null);
        return ResponseEntity.ok(result);
    }
}
